package edu.cdnu.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.cdnu.pojo.CourseStudentPojo;
import edu.cdnu.pojo.ResourcePojo;
import edu.cdnu.service.CourseService;
import edu.cdnu.service.ResourceService;

/**
 * 面向切面
 *  在这记录数据
 * @author ASUS AsingZ
 */
@Aspect
@Component
public class RecordDataAspect {
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private CourseService courseService;
	// 定义切点
	@Pointcut("execution(* edu.cdnu.controller.FileController.fileDownload(..))")
	private void pointCut1() {}
	@Pointcut("execution(* edu.cdnu.controller.ResourceController.playChpater(..))")
	private void pointCut2() {}
	@Pointcut("execution(* edu.cdnu.controller.CatalogueController.selectCatalogueDtoListByCourseIdAndState(..))")
	private void pointCut3() {}
	// 捕获
	@Before("pointCut1() || pointCut2()")
	public void before(JoinPoint joinPoint) {
		Object[] args=joinPoint.getArgs();
		String path=String.valueOf(args[0]);
		ResourcePojo resourcePojo=new ResourcePojo();
		resourcePojo.setResourceUrl(path);
		
		resourcePojo=resourceService.selectResourceByResourcePojo(resourcePojo);
		if(resourcePojo!=null&&resourcePojo.getId()!=null) {
			resourceService.addResourceDownloadTime(resourcePojo.getId());
		}
		
		
	}
	/**
	 * 访问次数
	 * @param joinPoint
	 */
	@Before("pointCut3()")
	public void visit(JoinPoint joinPoint) {
		Object[] args=joinPoint.getArgs();
		// 判断有没得这个参数 
		if(args[2]==null) {
			return ;
		}
		
		int courseId=Integer.parseInt(args[0].toString());
		int studentId=Integer.parseInt(args[2].toString());
		CourseStudentPojo courseStudentPojo=courseService.selectCourseStudentPojoByCourseIdAndStudentId(courseId, studentId);
		// 判断是否为空
		if(courseStudentPojo!=null) {
			// 不为空是有记录，增加访问量
			courseService.addCourseStudentVisitTime(courseStudentPojo.getId());
		}else {
			// 为空是没有记录数据，创建访问数据
			CourseStudentPojo newpojo=new CourseStudentPojo();
			newpojo.setCourseId(courseId);
			newpojo.setStudentId(studentId);
			courseService.addOrUpdateCourseStudent(newpojo);
		}
	}
}
